var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var router = require('./routes/router');
var db = require('./libs/db');

var expressJwt = require("express-jwt");
var jwt = require("jsonwebtoken");
require('./routes/ws');
var schedule = require("node-schedule");
var app = express();
app.maxSockets = 20;
//身份验证--------------
app.use(expressJwt({secret: "secret"}).unless({path: ['/api/ac_findUserResults','/api/findArea','/api/declare','/api/activ_addTribeUser','/api/activ_queryTribeUser','/api/activ_addUser','/api/activity_getActivityTime','/api/msocket-sendMessage','/api/manager_logins','/api/getscreendata','/api/ac_findDPResultList','/api/getrcode','/api/manager_tableTotal','/api/szyx_joinEvent','/api/szyx_createFirstUser','/api/szyx_updateUser','/api/szyx_createUser','/api/szyx_getToken','/api/getWXuserinfo','/api/wx_order','/api/wx_getOpendId','/table1.xlsx','/table2.xlsx','/table3.xlsx','/table4.xlsx','/api/manager_login','/api/ac_findActivityList','/api/ac_findList','/api/ac_add','/api/activity_faa','/api/activity_findThisResult','/api/activity_start','/api/activity_end','/api/verifySms', '/api/smssend', '/api/login', '/api/register']}));
app.use(function (err, req, res, next) {
    var url = req.url.substr(5,4);
    if (err.name === "UnauthorizedError" && url!='bmfw') {
        res.status(401).send("invalid token");
    } else {
        next();
    }
});
//身份验证--------------


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//设置跨域访问
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS');
    console.log('新的请求');
    if (req.method == 'OPTIONS') {
        res.send(200);
    }
    else {
        next();
    }
});
app.use('/api', router);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);

    res.render('error');

});

db.sequelize.sync({force: false}).then(function () {
    console.log("Server successed to start");
}).catch(function (err) {
    console.log("Server failed to start due to error: %s", err);
});
var rule = new schedule.RecurrenceRule();
rule.hour = 18;
var j = schedule.scheduleJob(rule, function(){
    console.log('现在时间：',new Date());
    var url = 'http://gys.jiyouhome.com/api-inquiry-sheet';
    request({
        url: url,
        method: 'POST',
        headers: {
            "Content-Type": "application/json;charset=utf-8",
        },
        body: formData
    }, function(err, response, body) {
    })
});

module.exports = app;
